package com.caiden_micheal.service.impl;

import com.caiden_micheal.base.utils.JwtUtil;
import com.caiden_micheal.base.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.jmreport.api.JmReportTokenServiceI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class JmReportTokenServiceIImpl implements JmReportTokenServiceI {
    private static final Logger logger = LoggerFactory.getLogger(JmReportTokenServiceIImpl.class);


    @Override
    public String getToken(HttpServletRequest request) {
        try {
            String token = request.getParameter("token");
            if (token == null) {
                token = request.getHeader("token");
            }
            return token;
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }
    }

    @Override
    public String getUsername(String token) {
        Claims claims = JwtUtil.validateUserToken(token);
        assert claims != null;
        return String.valueOf(claims.get("username"));
    }

    @Override
    public String[] getRoles(String token) {
        return new String[]{};
    }

    @Override
    public Boolean verifyToken(String token) {
        Claims claims = JwtUtil.validateUserToken(token);
        if (claims == null) {
            logger.warn("Identity verification failed. Token: " + token);
            return false;
        }
        // 验证用户是否登录状态
        String onlineStatusKey = "caiden_micheal:user:" + claims.get("userId") + ":onlineStatus";
        String onlineStatus = RedisUtil.getValue(onlineStatusKey);
        if (StringUtils.isEmpty(onlineStatus)) {
            logger.warn("This token has expired, please login again: " + token);
            return false;
        } else if (!Objects.equals(onlineStatus, claims.get("flag"))) {
            logger.warn("Token is used maliciously, and the current behavior has been recorded: " + token);
            return false;
        }
        return true;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        Map<String, Object> map = new HashMap(5);
        map.put(SYS_USER_CODE, this.getUsername(token));
        map.put(SYS_ORG_CODE, null);
        return map;
    }
}
